import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let TutorialManager = require("../../Tutorials/TutorialManager");

  const GAME_ICON_ID = "";

  /**
   * 显示Icon推荐位, icon子数组显示时的以iconsRef作为参考节点,
   * @param opts
   * @returns {*}
   */
  let showGameIcon = function (opts) {
    //新手引导时, 不显示icon推荐位
    if (TutorialManager.instance && TutorialManager.instance.tutorialsRunning())
      return null;

    let styles = getIconStyles(opts);
    return _showGameIconWithStyles(styles);
  };

  /**
   * 隐藏icon
   */
  let hideGameIcon = function (iconHandle) {
    if (!iconHandle)
      return;
    iconHandle.destroy();
  };


  let _showGameIconWithStyles = function (styles) {
    if (wx.createGameIcon === undefined) {
      console.log("icon推荐位初始化失败,微信版本太低");
      return null;
    }
    let icon = wx.createGameIcon({
      adUnitId: GAME_ICON_ID,
      count: styles.length,
      style: styles
    });
    icon.onLoad(() => {
      console.log('icon推荐位加载成功');
      icon.show();
    });
    icon.onError(err => {
      console.log('icon加载失败:', err);
    });
    icon.load();

    return icon;
  };

  let getIconStyles = function (opts) {
    let ratio = cc.view.getDevicePixelRatio();
    let scaleX = cc.view.getScaleX() / ratio;
    let scaleY = cc.view.getScaleY() / ratio;

    let styles = [];
    for (let i = 0; i < opts.iconsRef.length; i++) {
      let refNode = opts.iconsRef[i];
      //参考node的boundingBox来显示Icon
      let boundingBox = refNode.getBoundingBoxToWorld();
      // 转换为pt坐标
      let width = boundingBox.width * scaleX;
      let height = boundingBox.height * scaleY;
      let size = Math.min(width, height);
      let left = boundingBox.x * scaleX;
      let top = cc.view.getFrameSize().height - (boundingBox.y * scaleY) - size; // 转换坐标系（左上角原点)

      if (size < 50) {
        console.warn('Icon参考节点宽度小于50, 自动扩充为50');
        let diff = 50 - size;
        size = 50;
        left -= diff / 2;
      }

      styles.push({
        left,
        top,
        size,
        appNameHidden: opts.appNameHidden,
        borderWidth: opts.borderWidth,
        borderColor: opts.borderColor,
        color: opts.color,
      })
    }
    return styles;
  };


  module.exports = {
    showGameIcon,
    hideGameIcon,
  };
}